<?php


namespace App\Http\Controllers;

use App\Internals\CourseInternal;
use App\Models\UserCourse;
use App\Models\UserLesson;
use App\Models\UserLessonDub;
use App\Models\UserStatus;
use App\Models\UserWeeklyStats;

class HistoryController extends Controller
{

    /*
     * @api get /study-api/lessons/histories 用户历史学习课程记录
     * @version 0.0.1
     * @group web
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     */
    public function lessons()
    {
        // “今天”“昨天”“三天前”“一周前”和“一个月前”
        $this->validate($this->request, [
            "page" => "integer|min:1",
            "pageSize" => "integer|max:100|min:5"
        ]);
        $page = intval($this->request->input("page", 1));
        $pageSize = intval($this->request->input("pageSize", 15));
        $query = UserLesson::ofUserhistory($this->userId);
        $total = $query->count();
        $items = [];
        if ($total) {
            $lessonsObj = $query->orderBy('id', 'desc')->forPage($page, $pageSize)->get();
            $lessonIds = [];
            /** @var UserLesson $lessonObj */
            foreach ($lessonsObj as $lessonObj) {
                $lessonIds[] = $lessonObj->getLessonId();
            }
            $lessonsInfo = CourseInternal::getLessons($lessonIds);
            foreach ($lessonsObj as $lessonObj) {
                $item = $lessonsInfo[$lessonObj->getLessonId()];
                $item['wordCount'] = $lessonObj->getWordCount();
                $item['isDub'] = $lessonObj->getIsDub();
                $historyCategory = $lessonObj->getHistoryCategory();
                $items[$historyCategory][] = $item;
            }
        }
        return $this->sendSuccessJson(['total'=>$total, 'items'=>$items]);
    }

    /*
     * @api delete /study-api/lessons/{lessonId}/history 删除用户历史学习课程记录
     * @version 0.0.1
     * @group web
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     */
    public function deleteLesson($lessonId)
    {
        /** @var UserLesson $lessonObj */
        $lessonObj = UserLesson::ofUserLesson($this->userId, $lessonId)->first();
        if ($lessonObj) {
            $lessonObj->setLastStudyTime(null);
            //$lessonObj->setIsDub(UserLesson::IS_FALSE);
            $lessonObj->save();
            // 删除录音记录
            //UserLessonDub::ofUserLesson($this->userId, $lessonId)->forceDelete();
        }
        return $this->sendSuccessJson();
    }


    /*
     * @api get /study-api/words/histories 用户历史阅读量记录
     * @version 0.0.1l
     * @group web
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{
     *  "2[等级]":{"weekly[柱状数据]":{"1[周]":{"wordCount[阅读量]":198,"evaluated[0未评测，1评测通过，2评测未通过]":0}},"studiedCount[已学习总量]":3000,"nextLevelCount[升级需要的量]":30}
     * }
     * }
     */
    public function words()
    {
        $this->validate($this->request, [
            "page" => "integer|min:1",
            "pageSize" => "integer|max:100|min:5"
        ]);
        $page = intval($this->request->input("page", 1));
        $pageSize = intval($this->request->input("pageSize", 15));
        $query = UserWeeklyStats::where('user_id', $this->userId);
        $total = $query->count();
        $items = [];
        $currentLevelWordCount = 0;
        $wordCount = 0;
        $hadStudied = UserLesson::ofUserhistory($this->userId)->where('sequence', '!=', 0)->exists();
        if ($total) {
            /** @var UserStatus $userStatusObj */
            $userStatusObj = UserStatus::where('user_id', $this->userId)->first();
            $wordCount = $userStatusObj->getWordCount();
            $userCourseObj = UserCourse::getCurrent($this->userId);
            if ($userCourseObj) {
                $currentLevelWordCount = $userCourseObj->getWordCount();
            }
            $weeklyStats = $query->orderBy('id', 'desc')->forPage($page, $pageSize)->get();
            $items = [];
            /** @var UserWeeklyStats $itemObj */
            foreach ($weeklyStats as $itemObj) {
                $items[$itemObj->getWeek()] = ['wordCount' => $itemObj->getWordCount()];
            }
            // 补全没有的星期
            $studyTime = UserStatus::getStudyTime($this->userId);
            $weekWordCount = 0;
            for ($week = 1; $week <= $studyTime['week']; $week++) {
                if (!isset($items[$week])) {
                    $items[$week] = ['wordCount' => $weekWordCount];
                } else {
                    // 累计
                    $weekWordCount += $items[$week]['wordCount'];
                    $items[$week]['wordCount'] = $weekWordCount;
                }
            }
        }
        return $this->sendSuccessJson([
            'total'=>$total,
            'items'=>$items,
            'currentLevelWordCount' => $currentLevelWordCount,
            'wordCount' => $wordCount,
            'hadStudied' => $hadStudied,
        ]);
    }
}
